//
//  DiscoverViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/11/27.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "DiscoverViewController.h"
#import "DiscoverItemCell.h"
#import "TitlesStrView.h"
#import "DiscoverClassModel.h"
#import "GoodsListModel.h"
#import "GoodsDetailViewController.h"

@interface DiscoverViewController () <UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) TitlesStrView *titleView;
@property (nonatomic, strong) NSMutableArray<DiscoverClassModel *> *titleArray;

@end

@implementation DiscoverViewController
#pragma mark - 网络请求
- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
        self.navigationItem.title = @"发现";
        _dataSource = [NSMutableArray array];
        _page = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
    [self responseBlock];
    
    [self getClassNetData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.titleView.frame = CGRectMake(0, 0, self.view.width, 32);
    [self.titleView setBorderWithTop:NO left:NO bottom:YES right:NO borderColor:[UIColor grayE5Color] borderWidth:0.5];
}

#pragma mark - Method
- (void)configure {
    [self hiddenShadowImage:NO];
    self.navigationItem.leftBarButtonItem = nil;
    
    [self.view addSubview:self.titleView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    [self.tableView clearExtendCellLine];
    [self.tableView registerNib:[UINib nibWithNibName:@"DiscoverItemCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
}

- (void)configureTitleView {
    NSMutableArray *titleStrArr = [[NSMutableArray alloc] init];
    for (DiscoverClassModel *model in self.titleArray) {
        [titleStrArr addObject:model.gtrcname];
    }
    [self.titleView setupWithTitleStrsArr:titleStrArr withIndex:0];
}

- (void)responseBlock {
    __block typeof(self) blockSelf = self;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        blockSelf.page = 1;
        [blockSelf getGoodsNetData:blockSelf.titleArray[blockSelf.titleView.currentIndex].gtrcid isSelectTitle:NO];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        blockSelf.page++;
        [blockSelf getGoodsNetData:blockSelf.titleArray[blockSelf.titleView.currentIndex].gtrcid isSelectTitle:NO];
    }];
    [self.tableView.mj_footer setHidden:YES];
    
    self.titleView.block = ^(NSInteger index) {
        blockSelf.page = 1;
        [blockSelf.dataSource removeAllObjects];
        [blockSelf getGoodsNetData:blockSelf.titleArray[index].gtrcid isSelectTitle:YES];
    };
}
#pragma mark - 网络请求
- (void)getClassNetData {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Find_Get_Goods_Class parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [blockSelf.titleArray removeAllObjects];
            for (NSDictionary *dic in responseObject[@"data"]) {
                DiscoverClassModel *model = [DiscoverClassModel mj_objectWithKeyValues:dic];
                [blockSelf.titleArray addObject:model];
            }
            [blockSelf configureTitleView];
            if (blockSelf.titleArray.count > 0) {
                [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
                [blockSelf getGoodsNetData:blockSelf.titleArray.firstObject.gtrcid isSelectTitle:NO];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getGoodsNetData:(NSString *)gtrcid isSelectTitle:(BOOL)isSelectTitle {
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Find_Get_Goods parameters:@{@"pageSize":PageSize,@"pageNumber":@(self.page),@"gtrcid":gtrcid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [blockSelf endRefresh];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dic = responseObject;
            [blockSelf getNetSuccess:dic shouldScrollTable:isSelectTitle];
        } else {
            [blockSelf getNetFailure];
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [blockSelf endRefresh];
        [blockSelf getNetFailure];
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics shouldScrollTable:(BOOL)shouldScroll {
    [self.tableView.mj_footer setHidden:YES];
    
    if ([dics[@"data"][@"totalRow"] integerValue] > self.dataSource.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (self.page == 1) {
        [self.dataSource removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *list = dics[@"data"][@"list"];
    if (list.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dic in list) {
        GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:dic];
        [self.dataSource addObject:model];
    }
    [self.tableView reloadData];
    if (self.dataSource.count > 0 && shouldScroll) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
}

- (void)uploadCollection:(BOOL)isCollection goodsModel:(GoodsListModel *)goodsModel {
    if (![self checkLogin]) {
        return;
    }
    
    NSString *url, *alertStr;
    if (isCollection) {
        url = URL_Save_Collect;
        alertStr = @"收藏成功";
    } else {
        url = URL_Cancel_Collect;
        alertStr = @"取消收藏成功";
    }
    
    __block typeof(self) blockSelf = self;
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setObject:goodsModel.gid forKey:@"gid"];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:alertStr animated:YES];
            goodsModel.iscollection = isCollection;
            if (isCollection) {
                goodsModel.collectioncount = [NSString stringWithFormat:@"%ld",goodsModel.collectioncount.integerValue+1];
            } else {
                goodsModel.collectioncount = [NSString stringWithFormat:@"%ld",goodsModel.collectioncount.integerValue-1];
            }
            [blockSelf.tableView reloadData];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DiscoverItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    GoodsListModel *model = self.dataSource[indexPath.row];
    [cell.iconImageView sd_setImageWithURL:GetUrl(model.gimg) placeholderImage:PlaceholderImageSmall changeContentModel:UIViewContentModeScaleAspectFill];
    cell.titleLabel.text = model.gname;
    cell.priceLabel.text = [NSString stringWithFormat:@"¥%@",model.gprice];
    cell.collectionLabel.text = [NSString stringWithFormat:@"%@人收藏",model.collectioncount];
    [cell setButtonSelected:model.iscollection];
    
    __block typeof(self) blockSelf = self;
    cell.block = ^(BOOL isCollection) {
        [blockSelf uploadCollection:!isCollection goodsModel:model];
    };
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [DiscoverItemCell getHeight];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GoodsListModel *model = self.dataSource[indexPath.row];
    if (!model.isshelves) {
        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
        return;
    }
    GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
    goodsDetailVC.type = GoodsDetailViewControllerTypeForNormal;
    goodsDetailVC.gid = model.gid;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getGoodsNetData:self.titleArray[self.titleView.currentIndex].gtrcid isSelectTitle:NO];
}
#pragma mark - Getters
- (TitlesStrView *)titleView {
    if (!_titleView) {
        _titleView = [[TitlesStrView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 32)];
    }
    return _titleView;
}
- (NSMutableArray<DiscoverClassModel *> *)titleArray {
    if (!_titleArray) {
        _titleArray = [[NSMutableArray alloc] init];
    }
    return _titleArray;
}

@end
